#include "py_editor_extension.hpp"
#include "data/editor_data.hpp"
#include "scripting/scripting_api.h"
#include "scripting/scripting_module.h"
#include "utils/log.hpp"
#include <fmt/format.h>

PythonEditorScript::PythonEditorScript(EditorTarget type, std::string title, const std::string &script_path): IEditorScript(type, std::move(title), script_path, g_current_module)
{
    
}

PythonEditorScript::~PythonEditorScript()
{
    
}

void PythonEditorScript::execute(const void* node)
{
    py::gil_scoped_acquire gil;
    switch (apply_target_) {
        case IEditorScript::eItem: m_.attr("main")((const ItemNode*)node); break;
        case IEditorScript::eDay: m_.attr("main")((const DayLevelNode*)node); break;
        case IEditorScript::eMonth: m_.attr("main")((const MonthLevelNode*)node); break;
        case IEditorScript::eYear: m_.attr("main")((const YearLevelNode*)node); break;
        default: L_ERROR("Unknown target type!"); break;
    }
}

IScript* PythonEditorScript::create(EditorTarget target, std::string title, std::string_view code, const std::string &script_path)
{
    auto script = new PythonEditorScript(target, std::move(title), script_path);
    if (!script->compile(code)) {
        delete script;
        script = nullptr;
    }
    return script;
}

bool PythonEditorScript::compile(const std::string_view& code)
{
    std::string name = fmt::format("editor_{:X}", (uintptr_t)this);
    return compile_module_code(code.data(), name.c_str());
}
